import java.lang.reflect.Field;

/**
 * @Author: linzp
 * @Date: 2023/03/08/17:07
 */


class Reflect {
    private int id = 1;
    private String name = "成员变量";
}

public class demo0308 {
    public static void main(String[] args) {
        try {
            //获得Class对象
            Class c = Class.forName("Reflect");
            //使用无参构造方法创建对象r
            Reflect r = (Reflect) c.newInstance();
            //获取指定类的私有属性name
            Field f = c.getDeclaredField("name");
            //取消访问检查
            f.setAccessible(true);
            f.set(r, "成员变量");
            System.out.println("name = " + f.get(r));
            //获得私有属性id
            Field fId = c.getDeclaredField("id");
            //取消访问检查
            fId.setAccessible(true);
            fId.setInt(r, 12);
            System.out.println("id = " + fId.getInt(r));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
/*
输出
name = 成员变量
id = 12
 */
